package servlet;

import domain.NingboGuarantee;
import domain.ZhejiangGuarantee;
import org.json.JSONArray;
import org.json.JSONObject;
import service.NingboGuaranteeService;
import service.ZhejiangGuaranteeService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class NingboGuaranteeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NingboGuaranteeService ningboGuaranteeService = new NingboGuaranteeService();
        request.setCharacterEncoding("UTF-8");
        List<NingboGuarantee> list = ningboGuaranteeService
                .selectByYear(Integer.parseInt(request.getParameter("year")));
        JSONArray jsonArray = new JSONArray();
        StringBuilder yanglaoSB = new StringBuilder();
        StringBuilder yiliaoSB = new StringBuilder();
        StringBuilder fuliyuanSB = new StringBuilder();
        StringBuilder fuwuSB = new StringBuilder();
        StringBuilder citySB = new StringBuilder();
        Set<String> set = new HashSet<>();
        for (NingboGuarantee zg : list) {

            if (zg.getTpye().equals("养老保险参保人数"))
                yanglaoSB.append(zg.getValue() + ",");
            if (zg.getTpye().equals("医疗保险参保人数"))
                yiliaoSB.append(zg.getValue() + ",");
            if (zg.getTpye().equals("社会福利院数"))
                fuliyuanSB.append(zg.getValue() + ",");
            if (zg.getTpye().equals("社区服务设施数"))
                fuwuSB.append(zg.getValue() + ",");
            if (set.add(zg.getCounty()))
                citySB.append(zg.getCounty() + ",");
        }

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("养老", yanglaoSB.substring(0,yanglaoSB.length()-1));
        jsonObj.put("医疗", yiliaoSB.substring(0,yiliaoSB.length()-1));
        jsonObj.put("福利院", fuliyuanSB.substring(0,fuliyuanSB.length()-1));
        jsonObj.put("服务设施", fuwuSB.substring(0,fuwuSB.length()-1));
        jsonObj.put("城市", citySB.substring(0,citySB.length()-1));
        jsonArray.put(jsonObj);

        response.setHeader("content-type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println(jsonArray.toString());
    }
}
